/**
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.aiwei.tdjk.controller.sys;

import com.aiwei.tdjk.bean.ZTree;
import com.aiwei.tdjk.common.Constants;
import com.aiwei.tdjk.controller.BaseController;
import com.aiwei.tdjk.entity.Job;
import com.aiwei.tdjk.service.JobService;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * <p>Version: 1.0
 */
@Controller
@RequestMapping(value = "/admin/sys/organization/job")
public class JobController extends BaseController<Job> {

    @Autowired
    private JobService jobService;


    @RequestMapping(value = {"", "main"}, method = RequestMethod.GET)
    public String main() {
        return viewName("main");
    }

    @RequestMapping(value = "tree", method = RequestMethod.GET)
    public String tree(
            HttpServletRequest request,
            @RequestParam(value = "isShow", required = false) boolean isShow,
            @RequestParam(value = "searchName", required = false) String searchName,
            @RequestParam(value = "async", required = false, defaultValue = "false") boolean async,
            Model model) {

        List<Job> models = null;

        if (!StringUtils.isEmpty(searchName)) {
            models = jobService.findAllByName(searchName);
//            if (!async) { //非异步 查自己和子子孙孙
//                searchable.removeSearchFilter("name_like");
//                List<M> children = baseService.findChildren(models, searchable);
//                models.removeAll(children);
//                models.addAll(children);
//            } else { //异步模式只查自己
//
//            }
        } else {
            if (!async) {  //非异步 查自己和子子孙孙
                models = jobService.findAllWithSort(isShow);
            } else {  //异步模式只查根 和 根一级节点
//                models = baseService.findRootAndChild(searchable);
            }
        }
        model.addAttribute("trees",
                convertToZtreeList(request.getContextPath(),models,async,true));

        return viewName("tree");
    }



    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String view(@PathVariable("id") long id, Model model) {
        getBooleanList(model);
        model.addAttribute("m", jobService.get(id));
        model.addAttribute(Constants.OP_NAME, "查看");
        return viewName("editForm");
    }


    @RequestMapping(value = "{id}/update", method = RequestMethod.GET)
    public String updateForm(@PathVariable("id") long jobId, Model model, RedirectAttributes redirectAttributes) {

        Job job = jobService.get(jobId);
        if (job == null) {
            redirectAttributes.addFlashAttribute(Constants.ERROR, "您修改的数据不存在！");
            return redirectToUrl(viewName("success"));
        }
        getBooleanList(model);
        model.addAttribute("m", job);
        model.addAttribute(Constants.OP_NAME, "修改");
        return viewName("editForm");
    }

    private void getBooleanList(Model model) {
        HashMap<String,String> booleanList = new HashMap<>();
        booleanList.put("true","显示");
        booleanList.put("false","不显示");
        model.addAttribute("booleanList",booleanList);
    }

    @RequestMapping(value = "{id}/update", method = RequestMethod.POST)
    public String update(Model model,@ModelAttribute("m") Job m, BindingResult result,
            RedirectAttributes redirectAttributes) {

        if (result.hasErrors()) {
            return updateForm(m.getId(), model, redirectAttributes);
        }
        jobService.update(m);
        redirectAttributes.addFlashAttribute(Constants.MESSAGE, "修改成功");
        return redirectToUrl("success");
    }


    @RequestMapping(value = "{id}/delete", method = RequestMethod.GET)
    public String deleteForm(@PathVariable("id") long id, Model model) {
        getBooleanList(model);
        model.addAttribute("m", jobService.get(id));
        model.addAttribute(Constants.OP_NAME, "删除");
        return viewName("editForm");
    }

    @RequestMapping(value = "{id}/delete", method = RequestMethod.POST)
    public String deleteSelfAndChildren(@PathVariable("id") long id,
            RedirectAttributes redirectAttributes, Model model) {

        Job m = jobService.get(id);
        if (m.getParentId() != null && m.getParentId() == 0) {
//            result.reject("您删除的数据中包含根节点，根节点不能删除");
            return deleteForm(m.getId(), model);
        }

        jobService.deleteSelfAndChild(m.getId(),m.getParentIds()+m.getId()+"/");
        redirectAttributes.addFlashAttribute(Constants.MESSAGE, "删除成功");
        return redirectToUrl("success");
    }

    @RequestMapping(value = "success")
    public String success() {
        return viewName("success");
    }

    /////////////////////////////////////ajax///////////////////////////////////////////////

    @RequestMapping(value = "ajax/load")
    @ResponseBody
    public Object load(
            HttpServletRequest request,
            @RequestParam(value = "async", defaultValue = "true") Boolean async,
            @RequestParam(value = "asyncLoadAll", defaultValue = "false") Boolean asyncLoadAll,
            @RequestParam(value = "searchName", required = false) String searchName,
            @RequestParam(value = "id", required = false) Long parentId,
            @RequestParam(value = "excludeId", required = false) Long excludeId,
            @RequestParam(value = "onlyCheckLeaf", required = false, defaultValue = "false") Boolean onlyCheckLeaf) {


//        M excludeM = baseService.get(excludeId);
        List<Job> models = null;
        if (!StringUtils.isEmpty(searchName)) {//按name模糊查
            models = jobService.findAllByName(searchName);
            if (!async || asyncLoadAll) {//非异步模式 查自己及子子孙孙 但排除
//                searchable.removeSearchFilter("name_like");
//                List<M> children = baseService.findChildren(models, searchable);
//                models.removeAll(children);
//                models.addAll(children);
            } else { //异步模式 只查匹配的一级

            }
        } else { //根据有没有parentId加载

//            if (parentId != null) { //只查某个节点下的 异步
//                searchable.addSearchFilter("parentId", SearchOperator.eq, parentId);
//            }
//            if (async && !asyncLoadAll) { //异步模式下 且非异步加载所有
//                //排除自己 及 子子孙孙
//                baseService.addExcludeSearchFilter(searchable, excludeM);
//            }

            if (parentId != null && !asyncLoadAll) {
//                models = baseService.findRootAndChild(searchable);
            } else {
                boolean isShow=true;
                models = jobService.findAllWithSort(isShow);
            }
        }

        return convertToZtreeList(request.getContextPath(),models,async && !asyncLoadAll && parentId != 0,onlyCheckLeaf);
    }


    @RequestMapping(value = "ajax/{parent}/appendChild")
    @ResponseBody
    public Object ajaxAppendChild(HttpServletRequest request, @PathVariable("parent") long parentId) {


        Job child = new Job();
        child.setName("新节点");
        jobService.appendChild(parentId, child);
        return convertToZtree(child, true, true);
    }

    @RequestMapping(value = "ajax/{id}/delete")
    @ResponseBody
    public Object ajaxDeleteSelfAndChildren(@PathVariable("id") Long id) {

        jobService.delete(id);
        return "{}";
    }

    @RequestMapping(value = "ajax/{id}/rename", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Object ajaxRename(HttpServletRequest request, @PathVariable("id") long id, @RequestParam("newName") String newName) {

        Job tree = jobService.get(id);
        tree.setName(newName);
        jobService.update(tree);
        return convertToZtree(tree, true, true);
    }


    @RequestMapping(value = "ajax/{sourceId}/{targetId}/{moveType}/move", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Object ajaxMove(
            @PathVariable("sourceId") Job source, @PathVariable("targetId") Job target,
            @PathVariable("moveType") String moveType) {

//        baseService.move(source, target, moveType);
        return "";
    }


    private List<ZTree> convertToZtreeList(String contextPath, List<Job> models, boolean async, boolean onlySelectLeaf) {
        List<ZTree> zTrees = Lists.newArrayList();

        if (models == null || models.isEmpty()) {
            return zTrees;
        }

        for (Job m : models) {
            ZTree zTree = convertToZtree(m, !async, onlySelectLeaf);
            zTrees.add(zTree);
        }
        return zTrees;
    }

    private ZTree convertToZtree(Job m, boolean open, boolean onlyCheckLeaf) {
        ZTree zTree = new ZTree();
        zTree.setId(m.getId());
        zTree.setpId(m.getParentId());
        zTree.setName(m.getName());
        zTree.setIconSkin(m.getIcon());
        zTree.setOpen(open);
//        zTree.setRoot(m.isRoot());
//        zTree.setIsParent(m.isHasChildren());

        if (onlyCheckLeaf && zTree.isIsParent()) {
            zTree.setNocheck(true);
        } else {
            zTree.setNocheck(false);
        }
        return zTree;
    }

}
